package control;
 
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Vector;


import utility.CapitalChar;
import utility.CharAt;

import utility.Index;
import utility.SplitOnNumeric;
import validation.*;
import dbmanager.*;
/**
 *@author
 *This class parse the command 
 *
 */
public class Command
{
	final char stringChar = '"';
	
	DBManager database ;
	String usrname;
	String Request; 

	Validation valid;
	GetIdName gin;
	String Spchar;
	int count;

	public Command()
	{
	}
	/**
	 *Parameterise constructors 
	*/
	public Command(String Request,DBManager database)
	{		
		this.Request = Request;
		this.database = database;
		gin = new GetIdName(database);
	
	}
	
	public Command(DBManager database)
	{
		this.database = database;
	}

	public Hashtable<Object,Object> getHashCommand(String table_name,String message,String Process) 
	{
		SpecialCharacter spCharactor = new SpecialCharacter();
		ResultSet rs = null;
		
		message = " "+ message;
		Hashtable<Object,Object> temp = new Hashtable<Object,Object>();

		char[] charArray= message.toCharArray();
		char Reqspchar;
		
		String ReqSpchar="";
		int index1=0;
		
		//int index=-1;
		Boolean flage=false;
		//*******problem: when index=0, it does not consider spchar at 0 index e.g ,aaa200 it shows index of nextspchar7 i.e no spchar message.    
		try
		{
			rs = database.getSelect("select spchar,beforeafter,plusminus,width,fieldname from command where msgtype = '"+table_name+"' and process = '"+Process+"' order by order1");
			while(index1!=-1)
			{
				index1 = spCharactor.getNextSpChar(index1,message.toCharArray());
				try
				{
					Reqspchar=charArray[index1];
					ReqSpchar=""+Reqspchar;
								
				} catch (Exception e1) 
				{
					break;
				}
				
				flage=false;
				//String tableID= gin.getId(table_name);
				//String validationID = gin.getId("validation");
				System.out.println("CommandParsing::parse():: THE MESSAGE IN THE COMMAND PARSING IS :--> "+message); 
				try 
				{
					flage=false;
					while(rs.next())
					{
						
						String spchar = rs.getString("spchar");
						String fieldname = rs.getString("fieldname");
						try
						{
							//Foe vt spchar =null so continue the process.
							if(spchar==null)
							{
								continue;
							}
							if(ReqSpchar.equals("#"))
							{
								flage=true;
								break;
							}
							if(spchar.equals(ReqSpchar))
							{
								flage=true;
								int start=0;
								int end=0; 
								int index = Index.indexOf(message, spchar);
								int count = Index.indexOf(message, spchar, index+1);
								if(count!=-1)
								{
									temp.put("ErrorInput", "Error In Input String");
									return temp;
								}
								String beforeafter = rs.getString("beforeafter");
								int plusminus = rs.getInt("plusminus");
								int width = rs.getInt("width");
								
								String value="";
								
								if(beforeafter.equals("before"))
								{
									if(message.charAt(index+1) == stringChar)
									{
										if(plusminus == 0)
											plusminus = spCharactor.getPrevSpChar(index,message.toCharArray());
										else
											plusminus = index - plusminus;
										
										start = plusminus;
										end = start+width;
									}
									else
									{
										//IF PLUSMINUS FIELD CONTAINS 0 AND AFTERBEFORE  CONTAINS BEFORE 
										//THEN START WITH PREVIOUS SPECIAL CHARECTOR+1
										
										//SIMILLARLY WIDTH FIELD CONTAINS 0 
										//THEN ENDS AT CURRENT SPECIAL CHARECTOR-1
										
										if(plusminus == 0)	  
											plusminus = spCharactor.getPrevSpChar(index,message.toCharArray());
										else
											plusminus = index - plusminus;
										
										if(width == 0)
											width = index - 1;
											
										start = plusminus;
										end = start+width;
										
										//System.out.println("start "+start);
										//System.out.println("end "+end);
									}	
									value = message.substring(start+1,end);
								//	System.out.println("\n"+value);
								}
								
								else if(rs.getString("beforeafter").equals("after"))
								{
									if(message.charAt(index+1)=='"')
									{
										start = index+plusminus+2;
										width = message.indexOf(stringChar, start+1);
										System.out.println("Width = "+width);
										end = width;
									}
									else
									{
										//SIMILLARLY WIDTH FIELD CONTAINS 0 AND AFTERBEFORE CONTAINS AFTER 
										//THEN WIDTH GOES UPTO NEXT SPECIAL CHARECTOR-1
										
										//IF PLUSMINUS FIELD CONTAINS 0  
										//THEN START WITH CURRENT SPECIAL CHARECTOR+1
										
										start = index+plusminus+1;
										if(width == 0)
											width = spCharactor.getNextSpChar(start,message.toCharArray());
										else
											width = start+width; 
										
										if(width == message.length())
											width = message.length();
										
										end = width;
										//System.out.println("start "+start);
										//System.out.println("end "+end);
									}
									value = message.substring(start,end);
									
									
									//Validation  
									//get Validation For Table 
						/*			try
									{
										ResultSet validRS = database.getSelect("select * from property_details where mid = (select PV from property_details where mid = "+tableID+" and pid = "+validationID+")and pid = "+gin.getId(fieldname));
										while(validRS.next())
										{
											String col = validRS.getString("VT");
											//	Checking for alphanumeric
											Isalphanumeric alpha = new Isalphanumeric(); 
											if(alpha.validate(col) == true)
											{
												String []ConditionValue = SplitOnNumeric.splitOnNumber(col);
												Class c = Class.forName("validation."+CapitalChar.makeFirstCharCapital(ConditionValue[0]));
												valid = (Validation)c.newInstance();
												
												if(valid.validate(value,ConditionValue[1]) == false)
												{
													System.out.println("CommandParsing::parse():: Validation Failed for Column : "+fieldname+" Value "+value);
													temp.put("ErrorInput", valid.getMessage()+" for "+fieldname);
												}
											}
											else
											{
												Class c = Class.forName("validation."+CapitalChar.makeFirstCharCapital(col));
												valid = (Validation)c.newInstance();
												if(valid.validate(value) == false)
												{
													System.out.println("CommandParsing::parse():: Validation Failed for Column : "+fieldname+" Value "+value);
													temp.put("ErrorInput", valid.getMessage()+" for "+fieldname);
												}
											}
										}
									}
									catch (ClassNotFoundException e) 
									{
										temp.put("ErrorInput", "Validation Class Not Found for "+fieldname+"& Contact to Administrator");
										System.out.println("CommandParsing::parse():: Exception : "+e.getMessage());
									}
									catch (Exception e) 
									{
										System.out.println("CommandParsing::parse():: Exception : "+e.getMessage());
									}
							*/
								}
								if(!value.equals("no$"))
									temp.put(fieldname,value);
								else
								{
									temp.clear();
									return temp;
								}
							}
							
							
						}
						catch (Exception e) 
						{
							System.out.println("CommandParsing::parse():: Special Char Not Found");
							//temp.put(fieldname,"no$");
							continue;
						}
					}
					rs.beforeFirst();
					if(flage==false)
					{
						temp.clear();
						temp.put("ErrorInput","spchar "+ReqSpchar+" is not present in "+table_name+" database ");
						return(temp);
					}
				} catch (SQLException e) {
					e.printStackTrace();
			}
				//return(temp);
			}
			rs.close();
		}
		catch (Exception e) 
		{
		}
		return(temp);
	}
	
	public Hashtable<Object,Object> checkError(Hashtable<Object,Object> tempProperty1, String tablename)
	{
		Hashtable<Object,Object> PropertyMap = new Hashtable<Object, Object>();
		try 
		{
			if(tempProperty1.get("pid").toString().equals("0"))
			{
				PropertyMap.put("ErrorInput","Error in "+tablename+ "unable to get the property i.e  pid " +gin.getItem(tempProperty1.get("pid").toString()));
			}
			if(tempProperty1.get("pv").toString().equals("0")&& tempProperty1.get("vt").toString().equals("no$"))
			{
				PropertyMap.put("ErrorInput","Error in:  " +tablename+ "  unable to get the property value for property : "+gin.getItem(tempProperty1.get("pid").toString()));
			}
		} 
		catch (Exception e) {
			PropertyMap.put("ErrorInput","Error in "+tablename+ "unable to get the property");
		}
		return PropertyMap;
	}
	/**
	 * In getCount it will count the of properties present in the 
	 * given string
	 * It fires the query through which it gets the specialCharter from trans_property_details
	 * by taking index of spchar it splits the given string into properties by 
	 * using initTransactionProperty method.
	 * @return count no. of properties of trans_property_details. 
	 *  
	 */
	
	public int getCountof(String message,String tablename,String process)
	{
		ResultSet rs;
		String PropertySPchar=" ";  
		String msg="";
		
		try
		{
			rs = database.getSelect("select fieldname,spchar from command where msgtype = '"+tablename+"' and process ='"+process+"' and order1>0 order by order1");
			while(rs.next())
			{
				try 
				{
					PropertySPchar = rs.getString("spchar");
					setSPchar(PropertySPchar);
					int i = Index.indexOf(message, PropertySPchar);
					if(i!=-1)
						break;
				}
				catch (Exception e) {
				}
			}
				
			msg = message;
			int i = 0;
			while(i<msg.length())
			{
				char ch = CharAt.CharAT(msg, i);
			    if(ch == PropertySPchar.toCharArray()[0])
			    	count ++;
				i++;
			}
			rs.close();
		}
		catch(Exception e)
		{
			return 0;
		}
		return count;
	}
		
	public void setSPchar(String Spchar1) 
	{
		 this.Spchar=Spchar1;		
	}
	public String getSPchar() 
	{
		return Spchar;		
	}
	
	
	
	/**
	 * this function returns hashtable containing details of message in pool format
	 * from the given message
	 * @param table_name
	 * @param message
	 * @param Process
	 * @return
	 */
	public Hashtable<Object,Object> getHash(String table_name,String message,String Process)
	{
		
		ResultSet rs = null;
		Hashtable<Object,Object> temp = new Hashtable<Object, Object>();
		SpecialCharacter spCharactor = new SpecialCharacter();
		
	 	try
		{
			rs = database.getSelect("select spchar,beforeafter,plusminus,width,fieldname from command where msgtype = '"+table_name+"' and process = '"+Process+"' order by order1");
			
			while (rs.next())
			{
				
				String spchar = rs.getString("spchar");
				String fieldname = rs.getString("fieldname");
				try
				{
					//Foe vt spchar =null so continue the process.
					if(spchar==null)
					{
						continue;
					}
					
					if(message.contains(spchar))
					{
						//flage=true;
						int start=0;
						int end=0; 
						int index = Index.indexOf(message, spchar);
						int count = Index.indexOf(message, spchar, index+1);
						if(count!=-1)
						{
							temp.put("ErrorInput", "Error In Input String");
							return temp;
						}
						String beforeafter = rs.getString("beforeafter");
						int plusminus = rs.getInt("plusminus");
						int width = rs.getInt("width");
						
						String value="";
						
						if(beforeafter.equals("before"))
						{
							if(message.charAt(index+1) == stringChar)
							{
								if(plusminus == 0)
									plusminus = spCharactor.getPrevSpChar(index,message.toCharArray());
								else
									plusminus = index - plusminus;
								
								start = plusminus;
								end = start+width;
							}
							else
							{
								//IF PLUSMINUS FIELD CONTAINS 0 AND AFTERBEFORE  CONTAINS BEFORE 
								//THEN START WITH PREVIOUS SPECIAL CHARECTOR+1
								
								//SIMILLARLY WIDTH FIELD CONTAINS 0 
								//THEN ENDS AT CURRENT SPECIAL CHARECTOR-1
								
								if(plusminus == 0)	  
									plusminus = spCharactor.getPrevSpChar(index,message.toCharArray());
								else
									plusminus = index - plusminus;
								
								if(width == 0)
									width = index - 1;
									
								start = plusminus;
								end = start+width;
								
								//System.out.println("start "+start);
								//System.out.println("end "+end);
							}	
							value = message.substring(start+1,end);
						//	System.out.println("\n"+value);
						}
						
						else if(rs.getString("beforeafter").equals("after"))
						{
							if(message.charAt(index+1)=='"')
							{
								start = index+plusminus+2;
								width = message.indexOf(stringChar, start+1);
								System.out.println("Width = "+width);
								end = width;
							}
							else
							{
								//SIMILLARLY WIDTH FIELD CONTAINS 0 AND AFTERBEFORE CONTAINS AFTER 
								//THEN WIDTH GOES UPTO NEXT SPECIAL CHARECTOR-1
								
								//IF PLUSMINUS FIELD CONTAINS 0  
								//THEN START WITH CURRENT SPECIAL CHARECTOR+1
								
								start = index+plusminus+1;
								if(width == 0)
									width = spCharactor.getNextSpChar(start,message.toCharArray());
								else
									width = start+width; 
								
								if(width == message.length())
									width = message.length();
								
								end = width;
								//System.out.println("start "+start);
								//System.out.println("end "+end);
							}
							value = message.substring(start,end);
							
							
						}
						if(!value.equals("no$"))
							temp.put(fieldname,value);
						else
						{
							temp.clear();
							return temp;
						}
					}					
				}
				catch (Exception e) 
				{
					System.out.println("CommandParsing::parse():: Special Char Not Found");
					continue;
				}
			}
			
			
		}
		catch (Exception e) {
			// TODO: handle exception
		}
				
		return temp;
	}
	
	
	public static void main(String[] args) 
	{	
		DBManager db = new DBManager();
		db.getConnect();		
		String message="11 master_table add*StorageA#605";
		String table_name="master_table";
		String Process="add";
		Command c=new Command(db);
		Hashtable<Object,Object> msg1 = c.getHashCommand(table_name, message, Process);
		System.out.println("The sms is "+msg1);
	}
	
}
